package com.iqik.rocket.service.impl;

import com.iqik.rocket.dao.OrderRepository;
import com.iqik.rocket.pojo.Order;
import com.iqik.rocket.pojo.OrderStatus;
import com.iqik.rocket.service.OrderService;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.client.producer.SendCallback;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.Optional;
import java.util.UUID;

@Slf4j
@Service
public class OrderServiceImpl implements OrderService {

    @Autowired
    private RocketMQTemplate rocketMQTemplate;

    @Autowired
    private RedisTemplate<String, Integer> redisTemplate;

    @Autowired
    private OrderRepository orderRepository;

    @Override
    public String createOrder(String goodId) {
        int count = redisTemplate.opsForValue().get("good_count");
        if (count <= 0){
            return "false";
        }

        Order order = new Order();
        order.setId(UUID.randomUUID().toString());
        order.setGoodId(goodId);
        order.setCreateTime(new Date());
        order.setStatus(OrderStatus.NEW);
        rocketMQTemplate.asyncSend("tp_order_02", order, new SendCallback() {
            @Override
            public void onSuccess(SendResult sendResult) {
                log.info("发送消息 订单的id： " + sendResult.getMsgId());
                redisTemplate.opsForValue().set("good_count", count - 1);
            }

            @Override
            public void onException(Throwable throwable) {
                log.error("发生错误：" + throwable.toString());
                order.setStatus(null);
            }
        });
        return order.getStatus() == null ? "false": order.getId();
    }

    @Override
    public String payOrder(String id) {
        Order order = orderRepository.findById(id).get();
        if (order != null) {
            switch (order.getStatus()) {
                case NEW:
                    orderRepository.updateOrder(id, OrderStatus.PAYED);
                    return "已完成支付，请勿重复操作";
                case PAYED:
                    return "请勿重复操作";
                case CANCEL:
                    return "订单已取消";
            }
        }
        return "订单不存在";
    }
}
